package com.yehun.admin.socket;

import com.yehun.shiro.ShiroUser;
import com.yehun.utils.JsonUtils;
import com.yehun.web.websocket.SpringHandshakeInterceptor;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

public class SocketHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(SpringHandshakeInterceptor.class);

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            HttpSession session = serverHttpRequest.getServletRequest().getSession();
            Map parameterMap = serverHttpRequest.getServletRequest().getParameterMap();
            logger.info("SocketHandshakeInterceptor.beforeHandshake, parameterMap={}", JsonUtils.serialize(parameterMap));
            if (session != null) {
                logger.info("SocketHandshakeInterceptor.beforeHandshake, attributeNames={}", JsonUtils.serialize(session.getAttributeNames()));
                Object object = SecurityUtils.getSubject().getPrincipal();
                if (object != null) {
                    ShiroUser shiroUser = (ShiroUser) object;
                    attributes.put("currentUser", shiroUser);
                }
            }
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {
        super.afterHandshake(request, response, wsHandler, exception);
    }
}
